package com.cdel.akka.watcher;

import akka.actor.ActorRef;
import akka.actor.Terminated;
import akka.actor.UntypedActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;

//定义一个监视者，本质上还是一个actor，但不同的是，他会在它的上下文中watch一个actor。如果将来这个被监视的actor退出终止，WatchActor
//就能收到一条Terminated消息，这里，我们简单的打印终止消息中的相关actor路径，并且关闭整个actorSystem
public class WatchActor extends UntypedActor {

	private final LoggingAdapter log = Logging.getLogger(getContext().system(), this);

	public WatchActor(ActorRef ref) {
		getContext().watch(ref);
	}

	@Override
	public void onReceive(Object msg) throws Throwable {
		if(msg instanceof Terminated){
			System.out.println(String.format("%s has terminated, shutting down system", ((Terminated)msg).getActor().path()));
			getContext().system().shutdown();
		}else{
			unhandled(msg);
		}
	}

}
